package com.sh.cloudrender.infrastructure.configuration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.sh.cloudrender.infrastructure.dal.mapper"})
@EnableTransactionManagement
public class MybatisPlusConfig {

    /**
     * 内置插件：接入分页插件、乐观锁插件
     *
     * @return 插件拦截器
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Bean(name = {"mysqlSqlSessionFactory"})
    @Primary
    public SqlSessionFactory configSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource rdsDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(rdsDataSource);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = {"mysqlTxManager"})
    @Primary
    public PlatformTransactionManager configTransactionManager(@Qualifier("mysqlDataSource") DataSource rdsDataSource) {
        return new DataSourceTransactionManager(rdsDataSource);
    }
}
